<?php
/**
 * Description of Model_group
 *
 * @author Meta Sanjaya
 */
class Model_group extends MY_Model {
    public function __construct() {
        parent::__construct();
    }

    /**
     *
     * @param int $id
     * @return Obj_Group
     */
    function get_group($id) {
        $query = $this->db->query("select * from `".DATABASE_ERP."`.`group` where `id` = $id");

        if($query->num_rows() < 1) {
            return false;
        }

        $group = $query->row();
        $group->child = $this->get_child_groups($group->id);

        return $group;
    }

    function get_child_groups($id) {
        $query = $this->db->query("select * from `".DATABASE_ERP."`.`group` where `parent` = $id");

        if($query->num_rows() < 1) {
            return array();
        }

        $groups = array();

        foreach ($query->result() as $group) {
            $group->child = $this->get_child_groups($group->id);
            $groups[] = $group;
        }

        return $groups;
    }

    /**
     *
     * @param string $name
     * @param int $parent
     * @return int
     */
    function add_group($name, $parent) {
        $this->db->query("replace into `".DATABASE_ERP."`.`group`(`name`,`parent`) values('$name', $parent)");
        return $this->db->insert_id();
    }
}
?>
